package com.maxd.controller.order;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gexin.fastjson.JSON;
import com.maxd.adapter.IgnoreSecurity;
import com.maxd.error.ExceptionEnum;
import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.CommonInfo;
import com.maxd.model.ExcelData;
import com.maxd.model.PublisherOrderDtoBean;
import com.maxd.model.UserInfo;
import com.maxd.modules.coupon.entity.CouponAmount;
import com.maxd.respository.common.CommonRepository;
import com.maxd.respository.order.OrderJpaRepository;
import com.maxd.respository.order.OrderRepository;
import com.maxd.respository.pdd.PddJpaRepository;
import com.maxd.respository.userinfo.UserJpaRepository;
import com.maxd.respository.userinfo.UserRepository;
import com.maxd.service.common.ICommonService;
import com.maxd.service.order.OrderService;
import com.maxd.utils.*;
import com.pdd.pop.sdk.common.util.JsonUtil;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.PopHttpClient;
import com.pdd.pop.sdk.http.api.pop.request.PddDdkGoodsZsUnitUrlGenRequest;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkGoodsZsUnitUrlGenResponse;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TbkActivityInfoGetRequest;
import com.taobao.api.response.TbkActivityInfoGetResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.QueryParam;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@Api(value = "订单管理", tags = {"订单管理"})
@RequestMapping(value = "/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderJpaRepository orderJpaRepository;
    @Autowired
    private UserJpaRepository userJpaRepository;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private OrderTask orderTask;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private CommonRepository commonRepository;


    @IgnoreSecurity
    @GetMapping("/selectJTKList")
    @ApiOperation("获取聚推客列表")
    public JSONObject selectJTKList(String page,String pageSize,String xcx_spread){
        String url="http://api.jutuike.com/union/act_list";
        Map<String,String> result=new HashMap<>();
        result.put("apikey",commonRepository.findOne(266).getValue());
        result.put("page",page);
        result.put("pageSize",pageSize);
        result.put("xcx_spread",xcx_spread);
        String resultStr = HttpClientUtil.doGet(url,result);
        return JSONObject.parseObject(resultStr);
    }

    @IgnoreSecurity
    @GetMapping("/getJTKUrl")
    @ApiOperation("获取聚推客列表")
    public JSONObject getJTKUrl(String act_id,String relationId){
        String url="http://api.jutuike.com/union/act";
        Map<String,String> result=new HashMap<>();
        result.put("apikey",commonRepository.findOne(266).getValue());
        result.put("act_id",act_id);
        result.put("sid",relationId);
        String resultStr = HttpClientUtil.doGet(url,result);
        return JSONObject.parseObject(resultStr);
    }


    @RequestMapping(value = "/getWyH5", method = RequestMethod.GET)
    @ApiOperation("秒有卷文娱直充")
    @ResponseBody
    @IgnoreSecurity
    public Result getWyH5(String userId) {
        if(StringUtils.isEmpty(userId)){
            userId="1";
        }
        CommonInfo appkey = commonRepository.findOne(30);
        Map<String,String> map=new HashMap<>();
        map.put("apkey",appkey.getValue());
        map.put("user_id",userId);
        String body = HttpClientUtil.doGet(Config.MIAOYOUQUN_URL+"/ls/getWyH5", map);
        return ResultUtil.success(JSONObject.parseObject(body));
    }

    @RequestMapping(value = "/getWyPlatform", method = RequestMethod.GET)
    @ApiOperation("秒有卷文娱直充")
    @ResponseBody
    @IgnoreSecurity
    public Result getWyPlatform() {
        CommonInfo appkey = commonRepository.findOne(30);
        Map<String,String> map=new HashMap<>();
        map.put("apkey",appkey.getValue());
        String body = HttpClientUtil.doGet(Config.MIAOYOUQUN_URL+"/ls/getWyPlatform", map);
        return ResultUtil.success(JSONObject.parseObject(body));
    }


    @GetMapping("/getTbUrl")
    @ApiOperation("淘宝活动链接")
    @IgnoreSecurity
    public Result getTbUrl(String activityId,String relationId){
        //获取淘宝的appkey
        CommonInfo one = commonRepository.findOne(6);
        //获取淘宝的秘钥
        CommonInfo two = commonRepository.findOne(7);
        CommonInfo pid = commonRepository.findOne(9);
        String[] s = pid.getValue().split("_");
//        TaobaoClient client = new DefaultTaobaoClient("https://eco.taobao.com/router/rest", one != null ? one.getValue() : Config.TaoAppKey, two != null ? two.getValue() : Config.TaoSecret);
//        TbkActivityInfoGetRequest req = new TbkActivityInfoGetRequest();
//        req.setAdzoneId(Long.parseLong(s[3]));//	mm_xxx_xxx_xxx的第三位
//        req.setRelationId(Long.parseLong(relationId));//渠道关系id
//        req.setActivityMaterialId(activityId);//官方活动会场ID，从淘宝客后台“我要推广-活动推广”中获取
//        TbkActivityInfoGetResponse rsp = null;
//        try {
//            rsp = client.execute(req);
//            return ResultUtil.success(JSONObject.parseObject(rsp.getBody()));
//        } catch (ApiException e) {//
//            e.printStackTrace();
//        }
        return ResultUtil.error(-200,"获取链接失败！");

    }


    @GetMapping("/getDmUrl")
    @ApiOperation("多麦链接转链")
    @IgnoreSecurity
    public Result getDmUrl(String relationId,String adsId){
        CommonInfo clientId = commonRepository.findOne(201);
        CommonInfo clientSecret = commonRepository.findOne(202);
        StringBuilder url=new StringBuilder("https://open.duomai.com/apis?");
        String str="{\"ads_id\":\""+adsId+"\",\"site_id\":\""+clientId.getValue()+"\",\"ext\":{\"euid\":\""+relationId+"\"}}";
        String timestamp=System.currentTimeMillis()/1000+"";
        String sign = clientSecret.getValue() + "app_key" + clientId.getValue() + "servicecps-mesh.cpslink.links.post" +
                "timestamp" + timestamp + str + clientSecret.getValue();
        String s = MD5Util.md5Encrypt32Upper(sign);
        url.append("app_key=").append(clientId.getValue()).append("&sign=").append(s).append("&service=cps-mesh.cpslink.links.post");
        url.append("&timestamp=").append(timestamp);
        String s1 = HttpClientUtil.doPostJson(url.toString(), str);
        return ResultUtil.success(JSON.parseObject(s1));
    }


    @GetMapping("/getElmUrl")
    @ApiOperation("获取饿了么链接")
    @IgnoreSecurity
    public Result getElmUrl(String relationId,String activityId){
        //获取淘宝的appkey
        CommonInfo one = commonRepository.findOne(6);
        //获取淘宝的秘钥
        CommonInfo two = commonRepository.findOne(7);
        CommonInfo pid = commonRepository.findOne(9);
        if(StringUtils.isEmpty(activityId)){
            CommonInfo activityIds = commonRepository.findOne(128);
            activityId=activityIds.getValue();
        }
        String[] s = pid.getValue().split("_");
        TaobaoClient client = new DefaultTaobaoClient("https://eco.taobao.com/router/rest", one != null ? one.getValue() : Config.TaoAppKey, two != null ? two.getValue() : Config.TaoSecret);
        TbkActivityInfoGetRequest req = new TbkActivityInfoGetRequest();
        req.setAdzoneId(Long.parseLong(s[3]));//	mm_xxx_xxx_xxx的第三位
        req.setRelationId(Long.parseLong(relationId));//渠道关系id
        req.setActivityMaterialId(activityId);//官方活动会场ID，从淘宝客后台“我要推广-活动推广”中获取
        TbkActivityInfoGetResponse rsp = null;
        try {
            rsp = client.execute(req);
            return ResultUtil.success(JSONObject.parseObject(rsp.getBody()));
        } catch (ApiException e) {//
            e.printStackTrace();
        }
        return ResultUtil.error(-200,"获取链接失败！");

    }

    @GetMapping("/getMtUrl")
    @ApiOperation("获取美团链接")
    @IgnoreSecurity
    public Result getMtUrl(String relationId,String activityId){
        if(StringUtils.isEmpty(activityId)){
            CommonInfo one = commonRepository.findOne(127);
            activityId=one.getValue();
        }
        CommonInfo appkey = commonRepository.findOne(123);
        CommonInfo clientSecret = commonRepository.findOne(124);
        Map<String,String> map=new HashMap<>();
        map.put("appkey",appkey.getValue());//	appkey
        map.put("sid",relationId);
        map.put("shortLink","1");//0表示获取长链 1表示获取短链
        map.put("linkType","4");
        map.put("actId",activityId);
        String[] array={"appkey","sid","shortLink","linkType","actId"};
        String sign = genSign(map, array, clientSecret.getValue());
        map.put("sign",sign);//请求签名，计算方法参考文档中签名(sign)生成逻辑
        String data = HttpClientUtil.doGet(Config.MT_Link, map);
        JSONObject jsonObject = com.alibaba.fastjson.JSON.parseObject(data);
        return ResultUtil.success(jsonObject.getString("data"));
    }

    @GetMapping("/getMtUrls")
    @ApiOperation("获取美团链接")
    @IgnoreSecurity
    public Result getMtUrls(String relationId,String activityId,String linkType){
        if(StringUtils.isEmpty(linkType)){
            linkType="1";
        }
//        CommonInfo one = commonRepository.findOne(127);
        CommonInfo appkey = commonRepository.findOne(123);
        CommonInfo clientSecret = commonRepository.findOne(124);
        Map<String,String> map=new HashMap<>();
        map.put("appkey",appkey.getValue());//	appkey
        map.put("sid",relationId);
        map.put("shortLink","1");//0表示获取长链 1表示获取短链
        map.put("linkType",linkType);
        map.put("actId",activityId);
        String[] array={"appkey","sid","shortLink","linkType","actId"};
        String sign = genSign(map, array, clientSecret.getValue());
        map.put("sign",sign);//请求签名，计算方法参考文档中签名(sign)生成逻辑
        String data = HttpClientUtil.doGet(Config.MT_Link, map);
        JSONObject jsonObject = com.alibaba.fastjson.JSON.parseObject(data);
        return ResultUtil.success(jsonObject.getString("data"));
    }

    /*@GetMapping("/getMtUrl")
    @ApiOperation("获取美团链接")
    @IgnoreSecurity
    public Result getMtUrl(String relationId,String linkType){
        if(StringUtils.isEmpty(linkType)){
            //兼容以前的版本
            linkType="1";
        }
        CommonInfo one = commonRepository.findOne(127);
        CommonInfo appkey = commonRepository.findOne(123);
        CommonInfo clientSecret = commonRepository.findOne(124);
        Map<String,String> map=new HashMap<>();
        map.put("key",appkey.getValue());//	appkey
        map.put("sid",relationId);
        map.put("linkType",linkType);
        map.put("actId",one.getValue());
        String[] array={"key","sid","linkType","actId"};
        String sign = genSign(map, array, clientSecret.getValue());
        map.put("sign",sign);//请求签名，计算方法参考文档中签名(sign)生成逻辑
        String data = HttpClientUtil.doGet(Config.MT_Link, map);
        JSONObject jsonObject = com.alibaba.fastjson.JSON.parseObject(data);
        return ResultUtil.success(jsonObject.getString("data"));
    }*/

    public static String genSign(Map<String,String> map,String[] array,String SECRET) {
        Arrays.sort(array);
        StringBuilder sb=new StringBuilder(SECRET);
        for(String str:array){
            sb.append(str).append(map.get(str));
        }
        sb.append(SECRET);
        return md5(sb.toString());
    }

    public static String md5(String source) {
        String md5Result = null;
        try {
            byte[] hash = org.apache.commons.codec.binary.StringUtils.getBytesUtf8(source);
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(hash);
            hash = messageDigest.digest();
            md5Result = Hex.encodeHexString(hash);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return md5Result;
    }


    @GetMapping("/selectItemIdByUrl")
    @ApiOperation("通过链接获取商品id")
    @IgnoreSecurity
    public Result selectItemIdByUrl(String content) {
        String id;
        if (content.contains("https://item.taobao.com/item.htm?id=")) {
             id = content.split("id=")[1];
        } else if (content.contains("https://detail.tmall.com/item.htm?id=")) {
             id = content.split("id=")[1];
        } else if (content.contains("&id=")) {
             id = content.split("&id=")[1].split("&")[0];
        } else if (content.contains("?id=")) {
             id = "?id=".split(content)[1].split("&")[0];
        }else if(content.contains("https://item.m.jd.com/product/")){
             id = content.substring(30,content.indexOf(".html"));
        }else if(content.contains("https://wqitem.jd.com/item/view?")){
            int i=content.indexOf("sku=");
             id = content.substring(i+4,content.indexOf("&"));
        }else if(content.contains("https://mobile.yangkeduo.com/goods.html?goods_id=")){
             id = content.substring(content.indexOf("goods_id=")+9,content.indexOf("&"));
        }else if(content.contains("https://mobile.yangkeduo.com/goods2.html?")){
             id = content.substring(content.indexOf("goods_id=")+9,content.length());
        }else{
            return  ResultUtil.error(9999,"没有找到商品，请去搜索！");
        }
        return ResultUtil.success(id);
    }


    @PostMapping("/selectItemIdByUrl")
    @ApiOperation("通过链接获取商品id")
    @IgnoreSecurity
    public Result selectItemIdByUrls(String content) {
        String id;
        Map<String, Object> map = new HashMap<>();
        if (content.contains("https://item.m.jd.com/product/")) {
            id = content.substring(30, content.indexOf(".html"));
            map.put("type", 1);
        } else if (content.contains("https://wqitem.jd.com/item/view?")) {
            int i = content.indexOf("sku=");
            id = content.substring(i + 4, content.indexOf("&"));
            map.put("type", 1);
        } else if (content.contains("https://mobile.yangkeduo.com/goods.html?goods_id=")) {
            id = content.substring(content.indexOf("goods_id=") + 9, content.indexOf("&"));
            map.put("type", 2);
        } else if (content.contains("https://mobile.yangkeduo.com/goods2.html?")) {
            id = content.substring(content.indexOf("goods_id=") + 9);
            map.put("type", 2);
        } else if (content.contains("m.suning.com/product")) {
            id = content.substring(content.indexOf("product/") + 8, content.lastIndexOf("/"));
            String supplierCode = content.substring(content.lastIndexOf("/") + 1, content.indexOf(".html"));
            map.put("supplierCode", supplierCode);
            map.put("type", 3);
        } else if (content.contains("m-goods.kaola.com")) {
            id = content.substring(content.lastIndexOf("product/") + 8, content.indexOf(".html"));
            map.put("type", 4);
        } else if (content.contains("vip.com")) {
            Map<String,String> param=new HashMap<>();
            param.put("apkey",commonRepository.findOne(30).getValue());
            param.put("key",commonRepository.findOne(239).getValue());
            param.put("source",Config.BASE_NAME);
            param.put("content",content);
            String body = HttpClientUtil.doGet("http://api.web.ecapi.cn/vip/changeCpsUrlToItem", param);
            JSONObject jsonObject = JSONObject.parseObject(body);
            String code = jsonObject.getString("code");
            if("200".equals(code)){
                JSONObject data = jsonObject.getJSONObject("data");
                JSONObject successMap = data.getJSONObject("successMap");
                JSONObject jsonObject1 = successMap.getJSONObject(content);
                id = jsonObject1.getString("goodsId");
                map.put("type", 5);
            }else{
                id="";
            }
        } else {
            id = getTwd(content);
            if(StringUtils.isEmpty(id)){
                String urls="https://v2.api.haodanku.com/dy_analyze_code";
                Map<String,String> maps=new HashMap<>();
                maps.put("apikey",commonRepository.findOne(238).getValue());
                maps.put("content",content);
                String stringJson = HttpClientUtil.doPost(urls, maps);
                JSONObject jsonObjects = JSONObject.parseObject(stringJson);
                String msg = jsonObjects.getString("msg");
                if("SUCCESS".equals(msg)){
                    JSONObject data = jsonObjects.getJSONObject("data");
                    String goodsId = data.getString("goods_id");
                    map.put("type", 6);
                    map.put("id", goodsId);
                    return ResultUtil.success(map);
                }else{
                    Pattern pattern = Pattern.compile("https?://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]");
                    Matcher matcher = pattern.matcher(content);
                    if(matcher.find()){String pddUrl = getPddUrl(matcher.group());
                        if(StringUtils.isNotEmpty(pddUrl)){
                            JSONObject jsonObject = com.alibaba.fastjson.JSON.parseObject(pddUrl);
                            JSONObject goods_zs_unit_generate_response = jsonObject.getJSONObject("goods_zs_unit_generate_response");
                            if(goods_zs_unit_generate_response!=null){
                                String url = goods_zs_unit_generate_response.getString("url");
                                id = url.substring(url.indexOf("goods_id=") + 9, url.indexOf("&"));
                                map.put("type", 2);
                                map.put("id", id);
                                return ResultUtil.success(map);
                            }
                        }
                    }
                }
            }else{
                map.put("type", 0);
                map.put("id", id);
                return ResultUtil.success(map);
            }
            return ResultUtil.error(9999, "没有找到商品，请去搜索！");
        }
        map.put("id", id);
        return ResultUtil.success(map);
    }



    public String getTwd(String content){
        try {
            String value = commonRepository.findOne(255).getValue();
            if("1".equals(value)){
                CommonInfo three = commonRepository.findOne(30);
                CommonInfo pid = commonRepository.findOne(9);
                //CommonInfo ze = commonRepository.findOne(90);
                CommonInfo tb = commonRepository.findOne(11);
            /*String pattern = ze.getValue();
            Pattern r = Pattern.compile(pattern);
            Matcher m = r.matcher(content);
            String group ="";
            if (m.find()) {
                group=m.group();
                System.out.println("match: " + group);
            }*/
                System.out.println("End");
                String apkey = Config.MIAOYOUQUN_Key;
                if (three != null) {
                    apkey = three.getValue();
                }
                String tbname=tb.getValue();
                Pattern p1 = Pattern.compile("[\u4e00-\u9fa5]");
                Matcher m1 = p1.matcher(tb.getValue());
                if (m1.find()) {
                    tbname= URLEncoder.encode(tb.getValue(), "utf-8");
                }
                String word = URLEncoder.encode(content, "utf-8");
                String url = Config.MIAOYOUQUN_URL + "/taoke/doTpwdCovert?apkey=" + apkey + "&pid="+pid.getValue()+"&biz_scene_id=2&content=" + word + "&tbname=" + tbname;

                String s = HttpClientUtil.doGet(url);
                if (com.alibaba.fastjson.JSON.parseObject(s).getString("code").equals("200")) {
                    String data = com.alibaba.fastjson.JSON.parseObject(s).getString("data");
                    String item_id = com.alibaba.fastjson.JSON.parseObject(data).getString("item_id");
                    String goodsUrl=Config.MIAOYOUQUN_URL+"/taoke/getTkMaterialItem?keyword="+item_id+"&pid="+pid.getValue()+"&tbname="+tbname+"&apkey="+apkey;
                    String s1 = HttpClientUtil.doGet(goodsUrl);
                    JSONObject jsonObject = JSONObject.parseObject(s1);
                    String code = jsonObject.getString("code");
                    if("200".equals(code)){
                        JSONArray data1 = jsonObject.getJSONArray("data");
                        if(data1!=null && data1.size()>0){
                            JSONObject jsonObject1 = data1.getJSONObject(0);
                            return jsonObject1.getString("item_id");
                        }
                    }
                    return null;
                }else{
                    return null;
                }
            }else{
                /*String appId=commonRepository.findOne(253).getValue();
                String appSecret=commonRepository.findOne(254).getValue();
                String time = DateUtil.createTime();
                String str="https://v3.api.haodanku.com/rest";
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("method","analyze.taoword");
                jsonObject.put("app_id",appId);
                jsonObject.put("date",time);
                jsonObject.put("taoword",content);
                String sign="app_id"+appId+"date"+time+"methodanalyze.taowordtaoword"+content+appSecret;
                jsonObject.put("sign",MD5Util.md5Encrypt32Upper(sign));
                String s = HttpClientUtil.doPostJson(str, jsonObject.toJSONString());
                JSONObject jsonObject1 = JSONObject.parseObject(s);
                String code = jsonObject1.getString("code");
                if("200".equals(code)){
                    JSONObject data = jsonObject1.getJSONObject("data");
                    return data.getString("itemid");
                }*/
                String appId=commonRepository.findOne(253).getValue();
                String appSecret=commonRepository.findOne(254).getValue();
                String time = DateUtil.createTime();
                String str="https://v3.api.haodanku.com/rest";
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("method","analyze.clipboard");
                jsonObject.put("app_id",appId);
                jsonObject.put("date",time);
                jsonObject.put("content",content);
                jsonObject.put("is_change","0");
                String sign="app_id"+appId+"content"+content+"date"+time+"is_change0methodanalyze.clipboard"+appSecret;
                jsonObject.put("sign",MD5Util.md5Encrypt32Upper(sign));
                String s = HttpClientUtil.doPostJson(str, jsonObject.toJSONString());
                JSONObject jsonObject1 = JSONObject.parseObject(s);
                String code = jsonObject1.getString("code");
                if("200".equals(code)){
                    JSONObject data = jsonObject1.getJSONObject("data");
                    return data.getString("item_id");
                }
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

    public String getPddUrl(String content){
        CommonInfo clientId = commonRepository.findOne(23);
        CommonInfo clientSecret = commonRepository.findOne(24);
        CommonInfo pdd = commonRepository.findOne(26);
        UserInfo userInfos = userRepository.getUserByPdd(pdd.getValue());
        PopClient client = new PopHttpClient(clientId.getValue(), clientSecret.getValue());
        PddDdkGoodsZsUnitUrlGenRequest request = new PddDdkGoodsZsUnitUrlGenRequest();
        String s1 = "{\"uid\":\"" + userInfos.getRelationId() + "\"}";
        request.setPid(userInfos.getPdd());
        request.setCustomParameters(s1);
        request.setSourceUrl(content);
        PddDdkGoodsZsUnitUrlGenResponse response = null;
        try {
            response = client.syncInvoke(request);
            return JsonUtil.transferToJson(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    @GetMapping("/tallyOrder")
    @ApiOperation("同步订单")
    @IgnoreSecurity
    public Result tallyOrderTao() {
        return orderTask.tallyOrderTao();
    }


    @GetMapping("/selectOrderCount")
    @ApiOperation("订单统计 根据日期统计不同的订单数量 金额")
    public Result selectOrderCount(String relationId,@ApiParam("1本日 2昨日 3本月 4上月") Integer day){
        Calendar calendar=Calendar.getInstance();
        Date time;
        if(day==2){
            day=1;
            calendar.add(Calendar.DATE,-1);
        }else if(day==4){
            calendar.add(Calendar.MONTH,-1);
        }
        time=calendar.getTime();
        //统计自己的订单
        List<Map<String, Object>> myOrder = orderRepository.selectOrderCountByRelationIdList(relationId, day, time);
        //统计团队的订单
        List<Map<String, Object>> teamOrder = orderRepository.selectOrderCountByInvitationIdList(relationId, day, time);
        Map<String,Object> order=new HashMap<>();
        order.put("myOrder",myOrder);
        order.put("teamOrder",teamOrder);
        return ResultUtil.success(order);
    }

    @GetMapping("/sumOrderMoney")
    @ApiOperation("累计到账收益")
    public Result sumOrderMoney(String relationId){
        return ResultUtil.success(orderRepository.selectOrderCountByInvitationIdList(relationId));
    }



    @GetMapping("/selectOrder")
    @ApiOperation("找回订单")
    public Result selectOrder(String orderNo) {
        return ResultUtil.success(orderRepository.findByTradeParentId(orderNo));
    }

    @GetMapping("/bindingOrder")
    @ApiOperation("绑定订单")
    public Result bindingOrder(String orderNo,String relation_id) {
        if(StringUtils.isBlank(relation_id)){
            return ResultUtil.error(-100,"您还不是会员，暂不能绑定订单！");
        }
        UserInfo userInfo = userRepository.getUserByRelationId(relation_id);
        if(userInfo==null){
            return ResultUtil.error(-100,"会员信息查询错误！");
        }
        PublisherOrderDtoBean byTradeParentId = orderRepository.findByTradeParentId(orderNo);
        if(byTradeParentId==null){
            return ResultUtil.error(-100,"订单信息查询错误！");
        }
        if(byTradeParentId.getRelation_id()!=0){
            return ResultUtil.error(-100,"订单已经被绑定，请不要重复绑定！");
        }
        byTradeParentId.setRelation_id(Long.parseLong(relation_id));
        orderTask.bindingOrder(byTradeParentId,userInfo,byTradeParentId.getPub_share_pre_fee());
        return ResultUtil.success();
    }


    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation("未使用")
    @ResponseBody
    public Result save(PublisherOrderDtoBean publisherOrderDtoBean) {
        return orderService.save(publisherOrderDtoBean);
    }

    @RequestMapping(value = "/orderList", method = RequestMethod.GET)
    @ApiOperation("获取所有用户下单信息列表")
    @ResponseBody
    public Result orderList(@RequestParam int page, @RequestParam int size,@RequestParam String phone,@RequestParam String nickName,@RequestParam String relationId,String gradeIndex) {
        Pageable pageable = PageRequest.of(page, size);
        return orderService.selectOrderList(pageable,phone,nickName,relationId,gradeIndex);
    }

    @RequestMapping(value = "/userOrderListExcel", method = RequestMethod.GET)
    @ApiOperation("获取所有用户下单信息列表")
    @IgnoreSecurity
    public void userOrderListExcel(@RequestParam String phone,@RequestParam String nickName,@RequestParam String relationId, HttpServletResponse response) throws Exception {
        List<Map<String, Object>> maps = orderService.selectOrderLists(phone, nickName, relationId);
        ExcelData data = new ExcelData();
        data.setName("订单用户");
        List<String> titles = new ArrayList();
        titles.add("编号");titles.add("昵称");titles.add("手机号");titles.add("下单数量");titles.add("创建时间");
        titles.add("性别");titles.add("邀请人");titles.add("等级");titles.add("支付宝");
        titles.add("余额");titles.add("积分");titles.add("备注");titles.add("来源");
        titles.add("状态");
        data.setTitles(titles);
        List<List<Object>> rows = new ArrayList();
        DecimalFormat df = new DecimalFormat("#########.##");
        for(Map<String,Object> userInfo:maps){
            List<Object> row = new ArrayList();
            row.add(userInfo.get("id"));row.add(userInfo.get("nick_name"));row.add(userInfo.get("phone"));
            row.add(userInfo.get("num"));
            row.add(userInfo.get("create_at"));
            String gender = String.valueOf(userInfo.get("gender"));
            if(StringUtils.isBlank(gender)||"0".equals(gender) || "null".equals(gender)){
                row.add("未知");
            }else if("1".equals(gender)){
                row.add("男");
            }else{
                row.add("女");
            }
            row.add(userInfo.get("invitation"));row.add(userInfo.get("grade"));row.add(userInfo.get("zhifubao"));
            String jifen = String.valueOf(userInfo.get("jifen"));
            if(StringUtils.isBlank(jifen)||"0".equals(jifen) || "null".equals(jifen)){
                row.add(0);
            }else{
                row.add(df.format(Float.parseFloat(jifen)));
            }
            String orderJifen = String.valueOf(userInfo.get("order_jifen"));
            if(StringUtils.isBlank(orderJifen)||"0".equals(orderJifen) || "null".equals(orderJifen)){
                row.add(0);
            }else{
                row.add(df.format(Float.parseFloat(orderJifen)));
            }
            row.add(userInfo.get("name"));
            String platform1 = String.valueOf(userInfo.get("platform"));
            if("wap".equals(platform1)){
                row.add("网站");
            }else if("app".equals(platform1)){
                row.add("app");
            }else if("weixin".equals(platform1)){
                row.add("微信公众号");
            }else if("mp".equals(platform1)){
                row.add("微信小程序");
            }else{
                row.add("未知");
            }
            if("true".equals(String.valueOf(userInfo.get("state")))){
                row.add("正常");
            }else{
                row.add("禁用");
            }
            rows.add(row);
        }
        data.setRows(rows);
        ExportExcelUtils.exportExcel(response,"用户列表.xlsx",data);
    }

    @RequestMapping(value = "/orderListByUserId", method = RequestMethod.GET)
    @ApiOperation("获取单个用户下单信息列表")
    @ResponseBody
    public Result orderListByUserId(@RequestParam Long userId,@RequestParam int page, @RequestParam int size) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size,Sort.by(order));
        return orderService.selectOrderListByUserId(userId,pageable);
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiOperation("用户端根据用户渠道获取订单")
    @ResponseBody
    public Result findByRelationId(@RequestParam Long relation_id, @RequestParam Integer tk_status, @RequestParam int page, @RequestParam int size) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        if (tk_status == 0) {
            return orderService.findByRelationId(relation_id, pageable);
        } else {
            return orderService.findByRelationIdAndStatus(relation_id, tk_status, pageable);
        }
    }

    @RequestMapping(value = "/invitation/list", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("用户端代理订单")
    public Result findByInvitationAndStatus(@RequestParam String relation_id, @RequestParam Integer tk_status, @RequestParam int page, @RequestParam int size) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        return ResultUtil.success(orderRepository.findByInvitationAndStatus(relation_id, tk_status, pageable));
    }

    @RequestMapping(value = "/getTotal/{tk_status}/{balance}", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("管理平台总计累计订单金额")
    public Result getTotal(@PathVariable int tk_status, @PathVariable int balance) {
        return ResultUtil.success(orderRepository.getTotal(tk_status, balance));
    }

    @RequestMapping(value = "/getTotalByTime/{tk_status}/{balance}", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("用户端和管理平台每月累计订单金额")
    public Result getTotalByTime(@PathVariable int tk_status, @PathVariable int balance, @RequestParam String time) {
        return ResultUtil.success(orderRepository.getTotalByTime(time, tk_status, balance));
    }

    @RequestMapping(value = "/getPaidCountNoRelation", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("管理平台按照日期查询订单数量")
    public Result getPaidCountNoRelation(@RequestParam String time) {
        return ResultUtil.success(orderRepository.getPaidCountNoRelation(time));
    }

    @RequestMapping(value = "/getTotalByTimeNoBalance/{tk_status}", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("用户端和管理平台每月累计订单金额不涉及对用户结算")
    public Result getTotalByTimeNoBalance(@PathVariable int tk_status, @RequestParam String time) {
        return ResultUtil.success(orderRepository.getTotalByTimes(time, tk_status));
    }

    @RequestMapping(value = "/getTotalNoBlance/{tk_status}", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("用户端和管理平台总计累计订单金额不涉及对用户结算")
    public Result getTotalNoBlance(@PathVariable int tk_status) {
        return ResultUtil.success(orderRepository.getTotals(tk_status));
    }

    @RequestMapping(value = "/list/top", method = RequestMethod.GET)
    @ApiOperation("管理平台分页获取订单")
    @ResponseBody
    public Result getOrderTopList(@RequestParam int page, @RequestParam int size) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        return ResultUtil.success(orderJpaRepository.findAll(pageable));
    }

    @RequestMapping(value = "/count", method = RequestMethod.GET)
    @ApiOperation("用户端和管理平台获取用户的当月预计收入")
    @ResponseBody
    public Result pubSharePreFeeCount(@RequestParam Long relation_id, @RequestParam int tk_status) {
        return orderService.pubSharePreFeeCount(relation_id, tk_status);
    }

    @RequestMapping(value = "/now/count", method = RequestMethod.GET)
    @ApiOperation("用户端和管理平台获取上级的当月预计收入")
    @ResponseBody
    public Result pubShareInvitationPreFeeCount(@RequestParam String relation_id, @RequestParam int tk_status) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Date now = new Date();
        return ResultUtil.success(orderRepository.pubShareInvitationPreFeeCount(relation_id, tk_status, sdf.format(now)));
    }

    @RequestMapping(value = "/invitation/count", method = RequestMethod.GET)
    @ApiOperation("用户端和管理平台获取上级的上月预计收入")
    @ResponseBody
    public Result pubShareInvitationPreFeeCountLast(@RequestParam String relation_id, @RequestParam int tk_status) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Calendar cal = Calendar.getInstance();
        //获取上个月的日期（上个月的今天）
        cal.setTime(new Date());
        cal.add(Calendar.MONTH, -1);
        Date date3 = cal.getTime();
        return ResultUtil.success(orderRepository.pubShareInvitationPreFeeCount(relation_id, tk_status, sdf.format(date3)));
    }

    @RequestMapping(value = "/last/count", method = RequestMethod.GET)
    @ApiOperation("用户端和管理平台获取用户的上月收入")
    @ResponseBody
    public Result pubSharePreFeeLastMonthCount(@RequestParam Long relation_id, @RequestParam int tk_status) {
        return orderService.pubSharePreFeeLastMonthCount(relation_id, tk_status);
    }

    @RequestMapping(value = "/paidCount/{relation_id}", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("用户端和管理平台获取用户的今日付款订单数量")
    public Result getPaidCount(@PathVariable String relation_id) {
        return orderService.getPaidCount(Long.valueOf(relation_id));
    }

    @RequestMapping(value = "/month/{relation_id}", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("用户端和管理平台获取用户的本月付款订单数量")
    public Result getPaidCountMonth(@PathVariable String relation_id) {
        return orderService.getMonthPaidCount(Long.valueOf(relation_id));
    }

    @RequestMapping(value = "/isNewsUser/{user_id}", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("检测是不是新用户")
    public Result isNewsUser(@PathVariable String user_id) {
        UserInfo one = userJpaRepository.getOne(Long.valueOf(user_id));
        if (one != null) {
            String newsUser = orderRepository.isNewsUser(Long.valueOf(one.getRelationId()));
            if (newsUser != null && Integer.parseInt(newsUser) > 0) {
                return ResultUtil.success();
            } else {
                return ResultUtil.error(ExceptionEnum.UNKNOW_ERROR);
            }
        } else {
            return ResultUtil.error(ExceptionEnum.UNKNOW_ERROR);
        }
    }

    @RequestMapping(value = "/trade_id/{trade_id}", method = RequestMethod.GET)
    @ApiOperation("管理平台统计会员")
    @ResponseBody
    public Result findByRelationIdCount(@PathVariable String trade_id) {
        return orderService.findByRelationIdCount(trade_id);
    }

    @RequestMapping(value = "/order/id/{order_id}", method = RequestMethod.GET)
    @ApiOperation("未使用 更新订单状态")
    @ResponseBody
    public Result updateOrderStatus(@PathVariable String order_id) {
        PublisherOrderDtoBean one = orderJpaRepository.findById(Long.valueOf(order_id)).orElse(null);
        assert one != null;
        one.setTk_status(13);
        return ResultUtil.success(orderJpaRepository.save(one));
    }

    /**
     * 管理平台查询用户订单
     *
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/page/{page}/size/{size}/status/{status}/from/{fromInfo}/relation/{relation}", method = RequestMethod.GET)
    @ApiOperation("管理平台查询用户订单")
    @ResponseBody
    public Result getAdminList(@PathVariable String relation, @PathVariable int page, @PathVariable int size, @PathVariable String status, @PathVariable String fromInfo) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        return orderService.getAdminList(fromInfo, Integer.valueOf(status), pageable, relation);
    }
    @RequestMapping(value = "/pageAll", method = RequestMethod.GET)
    @ApiOperation("所有用户订单")
    @ResponseBody
    public Result pageAll(
            @RequestParam String relation,
            @RequestParam int page,
            @RequestParam int size,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String fromInfo) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        Page<PublisherOrderDtoBean> all = orderJpaRepository.findAll((root, query, criteriaBuilder) -> {
            List<Predicate> conditions = new ArrayList<>();
            if (StringUtils.isNotBlank(relation)) {
                conditions.add(criteriaBuilder.equal(root.get("relation_id"), Long.parseLong(relation)));
            }
            if (StringUtils.isNotBlank(status)) {
                conditions.add(criteriaBuilder.equal(root.get("tk_status"), Integer.parseInt(status)));
            }
            if (StringUtils.isNotBlank(fromInfo)) {
                if (!"all".equals(fromInfo)) {
                    conditions.add(criteriaBuilder.equal(root.get("fromInfo"), fromInfo));
                }
            }
            query.where(
                    conditions.toArray(new Predicate[]{})
            );
            return query.getRestriction();

        }, pageable);
        return ResultUtil.success(all);
    }

    /**
     * 用户端查询团队订单
     *
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/team/page/{page}/size/{size}/status/{status}/from/{fromInfo}/relation/{relation}", method = RequestMethod.GET)
    @ApiOperation("用户端查询团队订单")
    @ResponseBody
    public Result getInvitationList(@PathVariable String relation, @PathVariable int page, @PathVariable int size, @PathVariable String status, @PathVariable String fromInfo) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        if (Integer.valueOf(status) == -1) {
            return ResultUtil.success(orderRepository.findByFromAndInvitation(fromInfo, relation, pageable));
        } else {
            return ResultUtil.success(orderRepository.findByFromAndInvitationAndStatus(Integer.valueOf(status), fromInfo, relation, pageable));
        }
    }

    /**
     * 用户端查询团队订单
     *
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/team/page/{page}/size/{size}/status/{status}/from/{fromInfo}/relation/{relation}/{type}", method = RequestMethod.GET)
    @ApiOperation("用户端查询团队订单")
    @ResponseBody
    public Result getInvitationList(@PathVariable String relation, @PathVariable int page, @PathVariable int size, @PathVariable String status, @PathVariable String fromInfo,@PathVariable("type") Integer type) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        if (Integer.valueOf(status) == -1) {
            if(type==1){
                return ResultUtil.success(orderRepository.findByFromAndInvitation(fromInfo, relation, pageable));
            }else{
                return ResultUtil.success(orderRepository.findByFromAndInvitations(fromInfo, relation, pageable));
            }
        } else {
            if(type==1){
                return ResultUtil.success(orderRepository.findByFromAndInvitationAndStatus(Integer.valueOf(status), fromInfo, relation, pageable));
            }else{
                return ResultUtil.success(orderRepository.findByFromAndInvitationAndStatuss(Integer.valueOf(status), fromInfo, relation, pageable));
            }
        }
    }

    /**
     * 管理获取订单 多条件筛选
     *
     * @return
     */
    @RequestMapping(value = "/orderList/{page}/{size}", method = RequestMethod.GET)
    @ApiOperation("管理获取订单 多条件筛选")
    @ResponseBody
    public Result orderList(@PathVariable int page, @PathVariable int size, String tradeId, @RequestParam int balance, @RequestParam String invitation, @RequestParam Long relation_id, @RequestParam int tk_status, @RequestParam String from) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        // 构造自定义查询条件
        Specification<PublisherOrderDtoBean> queryCondition = new Specification<PublisherOrderDtoBean>() {
            @Override
            public Predicate toPredicate(Root<PublisherOrderDtoBean> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (!invitation.equals("-1")) {
                    predicateList.add(criteriaBuilder.equal(root.get("invitation"), invitation));
                }
                if (!from.equals("all")) {
                    predicateList.add(criteriaBuilder.equal(root.get("fromInfo"), from));
                }
                if (relation_id != -1) {
                    predicateList.add(criteriaBuilder.equal(root.get("relation_id"), relation_id));
                }
                if (tk_status != -1) {
                    predicateList.add(criteriaBuilder.equal(root.get("tk_status"), tk_status));
                }
                if (balance != -1) {
                    predicateList.add(criteriaBuilder.equal(root.get("balance"), balance));
                }
                if (!"-1".equals(tradeId)) {
                    predicateList.add(criteriaBuilder.equal(root.get("trade_id"), tradeId));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        return ResultUtil.success(orderJpaRepository.findAll(queryCondition, pageable));
    }

    @RequestMapping(value = "/orderListExcel", method = RequestMethod.GET)
    @ApiOperation("导出管理获取订单 多条件筛选")
    @IgnoreSecurity
    public void orderListExcel(@RequestParam int balance, @RequestParam String invitation, @RequestParam Long relation_id, @RequestParam int tk_status, @RequestParam String from, HttpServletResponse response) throws Exception {
        Sort.Order orders = new Sort.Order(Sort.Direction.DESC, "id");
        PublisherOrderDtoBean publisherOrderDtoBean=new PublisherOrderDtoBean();
        if (!invitation.equals("-1")) {
            publisherOrderDtoBean.setInvitation(invitation);
        }
        if (!from.equals("all")) {
            publisherOrderDtoBean.setFromInfo(from);
        }
        if (relation_id != -1) {
            publisherOrderDtoBean.setRelation_id(relation_id);
        }
        if (tk_status != -1) {
            publisherOrderDtoBean.setTk_status(tk_status);
        }
        if (balance != -1) {
            publisherOrderDtoBean.setBalance(balance);
        }
        List<PublisherOrderDtoBean> all = orderRepository.selectOrderList(balance, invitation, relation_id, tk_status, from);
        ExcelData data = new ExcelData();
        if("all".equals(from)){
            data.setName("全部订单");
        }else if("tb".equals(from)){
            data.setName("淘宝订单");
        }else if("pdd".equals(from)){
            data.setName("拼多多订单");
        }else if("jd".equals(from)){
            data.setName("京东订单");
        }else{
            data.setName("未命名");
        }
        List<String> titles = new ArrayList();
        titles.add("商品编号");titles.add("商品图片");titles.add("商品名称");titles.add("会员号");
        titles.add("直属");titles.add("非直属");titles.add("订单号");titles.add("商品单价");titles.add("实付金额");
        titles.add("商品总佣金");titles.add("会员佣金");titles.add("直属佣金");titles.add("非直属佣金");titles.add("平台佣金");
        titles.add("支付时间");titles.add("来源渠道");titles.add("订单状态");titles.add("平台结算状态");
        data.setTitles(titles);
        List<List<Object>> rows = new ArrayList();
        for(PublisherOrderDtoBean order:all){
            List<Object> row = new ArrayList();
            row.add(order.getId());row.add("https:"+order.getItem_img());row.add(order.getItem_title());row.add(order.getRelation_id());
            row.add(order.getInvitation());row.add(order.getInvitations());row.add(order.getTrade_id());row.add(order.getItem_price());row.add(order.getAlipay_total_price());
            row.add(order.getPub_share_pre_fee());
            int tk_status1 = order.getTk_status();
            if(tk_status1==13){
                row.add(0);row.add(0);
                row.add(0);row.add(0);
            }else{
                row.add(order.getPub_share_pre_fee_user());row.add(order.getInvitationMoney());row.add(order.getInvitationMoneys());
                String pub_share_fee = order.getPub_share_pre_fee();
                Double fee=0.00;
                if(StringUtils.isBlank(pub_share_fee) || "0".equals(pub_share_fee) || "null".equals(pub_share_fee)){
                    fee=0.00;
                }else{
                    fee=Double.parseDouble(pub_share_fee);
                }
                String pub_share_pre_fee_user = order.getPub_share_pre_fee_user();
                Double feeUser=0.00;
                if(StringUtils.isBlank(pub_share_pre_fee_user) || "0".equals(pub_share_pre_fee_user) || "null".equals(pub_share_pre_fee_user)){
                    feeUser=0.00;
                }else{
                    feeUser=Double.parseDouble(pub_share_pre_fee_user);
                }
                String invitationMoney = order.getInvitationMoney();
                Double money=0.00;
                if(StringUtils.isBlank(invitationMoney) || "0".equals(invitationMoney) || "null".equals(invitationMoney)){
                    money=0.00;
                }else{
                    money=Double.parseDouble(invitationMoney);
                }
                String invitationMoneys = order.getInvitationMoneys();
                Double moneys=0.00;
                if(StringUtils.isBlank(invitationMoneys) || "0".equals(invitationMoneys) || "null".equals(invitationMoneys)){
                    moneys=0.00;
                }else{
                    moneys=Double.parseDouble(invitationMoneys);
                }
                fee=fee-feeUser;
                fee=fee-money;
                fee=fee-moneys;
                BigDecimal bg = new BigDecimal(fee).setScale(2, RoundingMode.UP);
                row.add(bg.doubleValue());
            }
            row.add(order.getTk_paid_time());
            if("tb".equals(order.getFromInfo())){
                row.add("淘宝");
            }else if("pdd".equals(order.getFromInfo())){
                row.add("拼多多");
            }else if("jd".equals(order.getFromInfo())){
                row.add("京东");
            }else if("elm".equals(order.getFromInfo())){
                row.add("饿了么");
            }else if("mt".equals(order.getFromInfo())){
                row.add("美团");
            }else if("dy".equals(order.getFromInfo())){
                row.add("抖音");
            }else if("jtk".equals(order.getFromInfo())){
                row.add("生活专区");
            }else{
                row.add("未命名");
            }
            if(tk_status1==3){
                row.add("订单结算");
            }else if(tk_status1==12){
                row.add("订单付款");
            }else if(tk_status1==13){
                row.add("订单失效");
            }else if(tk_status1==14){
                row.add("订单成功");
            }
            int balance1 = order.getBalance();
            if(balance1==0){
                row.add("未结算");
            }else{
                row.add("已结算");
            }
            rows.add(row);
        }
        data.setRows(rows);
        ExportExcelUtils.exportExcel(response,"订单列表.xlsx",data);
    }

    /**
     * 获取团队总收益
     *
     * @return
     */
    @RequestMapping(value = "/team/total/relation/{relation}", method = RequestMethod.GET)
    @ApiOperation("获取团队总收益")
    @ResponseBody
    public Result getTeamTotal(@PathVariable String relation) {
        CommonInfo one = commonRepository.findOne(91);
        if("1".equals(one.getValue())){
            return ResultUtil.success(orderRepository.countByTnvitationMoney(relation));
        }
        String count = orderRepository.countByTnvitationMoney(relation);
        String count1 = orderRepository.countByTnvitationMoneys(relation);
        double v =0.00;
        if(count!=null){
            v=Double.parseDouble(count);
        }
        double v1 =0.00;
        if(count1!=null){
            v1=Double.parseDouble(count1);
        }
        return ResultUtil.success(v+v1);
    }



    /**
     * 根据时间获取团队收益
     *
     * @return
     */
    @RequestMapping(value = "/team/time", method = RequestMethod.GET)
    @ApiOperation("根据时间和订单状态获取团队收益")
    @ResponseBody
    public Result getTeamTimeTotal(@RequestParam String relation, @RequestParam String time, @RequestParam int tk_status) {
        return ResultUtil.success(orderRepository.countByTnvitationAndTimeMoney(relation, time, tk_status));
    }

    @GetMapping("/selectZhiCount")
    @ApiOperation("查询直属粉丝")
    public Result selectZhiCount(String relationId){
        int i = userRepository.selectUserByZhiCount(relationId);
        return ResultUtil.success(i);
    }

}
